class Credit {
  // constructor
  constructor() {
    
    let that = this

    /* ========= 状态 ========= */
    // 是否已经连接到后台代码
    this.isConnectBackground = false
    // 是否已经连接到服务器
    this.isConnectServer = false
    // 是否正在执行任务
    this.isTask = false
    // 是否超时
    this.isTimeout = false
    // 页面是否已经加载完成
    this.isLoad = false
    // 判断是否已经登录
    this.isLogin = false
    // 每个任务的时间戳 
    this.stamp = null

    this.port = null

    this.data = null

    // 当前页面名称
    this.currentPage = ''

    /* ========= 页面元素 ========= */
    // DOM元素
    this.el_content = null
    this.el_main = null
    // jquery对象，用于方便获取load事件
    this.$content = null
    this.$main = null
    // frame路径
    this.url_content = ''
    this.url_main = ''

    /* ========= 用路径和页面元素特征判定页面的正则 ========= */
    this.match = {
      index: /index1.do/,
      login: /loginreg.jsp|login.do/,
      reg: /userReg.do/,
      regStep1: /step_a.png$/,
      regStep2: /step_b.png$/,
      regSuccess: /step_c.png$/,
      findPassword: /resetPassword.do/,
      findPasswordStep1: /./,
      findPasswordStep2: /./,
      findPasswordSuccess: /./,
      main: /login.do/,
      welcome: /welcome.do/,
      applicationReport: /applicationReport|submitQS/,
      applicationReportSuccess: /submitKBA/,
      getQues: /checkishasreport/,
      getReport: /queryReport/,
      viewReport: /simpleReport.do/,
      download: /reportAction.do/
    }
    
    /* ========= 哪些页面不需要登录权限 ========= */
    this.noLoginMatch = ['index', 'login', 'reg', 'regStep1', 'regStep2', 'regSuccess', 'findPassword', 'findPasswordStep1', 'findPasswordStep2', 'findPasswordSuccess']

    /* ========= 哪些页面不可以手动跳转，比如注册成功 ========= */
    this.noJumpMatch = ['regStep2', 'regSuccess', 'findPasswordStep2', 'findPasswordSuccess', 'getQues', 'viewReport', 'download']

    /* ========= 每个页面的url ========= */
    this.url = {
      index: '/index1.do',
      login: '/page/login/loginreg.jsp',
      reg: '/userReg.do?method=initReg',
      welcome: {
        content: '/login.do',
        main: '/welcome.do'
      },
      applicationReport: {
        content: '/login.do',
        main: '/reportAction.do?method=applicationReport'
      },
      getReport: {
        content: '/login.do',
        main: '/reportAction.do?method=queryReport'
      }
    }
    

    if (window.document.readyState === 'complete') {
      this.isLoad = true
      console.log('初始化')
      this.connect()
    } else {
      $(window).on('load', function() {
        that.isLoad = true
        console.log('等了一会才初始化')
        that.connect()
      })
    }

  }
  
  getPageName() {

    let that = this,
        loc  = window.location.href

    // 检查页面是否加载完成
    if (!this.isLoad) {
      console.log('页面未加载完成')
      

       false
    }

    this._reload()
    
    // 报告结果 和 下载合同 这个两个页面是单独的页面，需要单独根据url地址判断
    // 报告结果
    if (this.match.viewReport.test(loc)) {
      this.isLogin = true
      this.currentPage = 'viewReport'

      console.log('报告结果')
      return 'viewReport'
    }
    
    // 下载合同 这个页面没有jquery
    if (this.match.download.test(loc)) {
      this.isLogin = true
      this.currentPage = 'download'

      console.log('下载合同')
      return 'download'
    }

    // 先根据是否存在mainFrame判断是否登录，存在mainFrame则表示已经登录
    if (!this.el_main) { //未登录
      this.isLogin = false
      
      // 主页
      if (this.match.index.test(this.url_content)) {
        console.log('主页')
        this.currentPage = 'index'
        return 'index'
      }
      
      // 登录
      if (this.match.login.test(this.url_content)) {
        console.log('登录页')
        this.currentPage = 'login'
        return 'login'
      }
      
      // 注册，下面还分一、二和成功步骤
      if (this.match.reg.test(this.url_content)) {
        
        // 注册步骤根据页面某个图片的src来判断，这个不靠谱
        let src = $(this.el_content.document).find('.step_a img').attr('src')

        // 注册步骤一
        if (this.match.regStep1.test(src)) {
          console.log('注册步骤一')
          this.currentPage = 'regStep1'
          return 'regStep1'
        }
        
        // 注册步骤二
        if (this.match.regStep2.test(src)) {
          console.log('注册步骤二')
          this.currentPage = 'regStep2'
          return 'regStep2'
        }
        
        // 注册步骤三
        if (this.match.regSuccess.test(src)) {
          console.log('注册成功')
          this.currentPage = 'regSuccess'
          return 'regSuccess'
        }

      }

    } else { // 已登录
      this.isLogin = true
      
      // 欢迎页
      if (this.match.welcome.test(this.url_main)) {
        console.log('欢迎页')
        this.currentPage = 'welcome'
        return 'welcome'
      }
      
      // 请求报告
      if (this.match.applicationReport.test(this.url_main)) {
        console.log('请求报告')
        this.currentPage = 'applicationReport'
        return 'applicationReport'
      }
      
      // 请求报告成功
      if (this.match.applicationReportSuccess.test(this.url_main)) {
        console.log('请求报告成功')
        this.currentPage = 'applicationReportSuccess'
        return 'applicationReportSuccess'
      }
      
      // 获取报告
      if (this.match.getReport.test(this.url_main)) {
        console.log('获取报告')
        this.currentPage = 'getReport'
        return 'getReport'
      }
      
      // 问卷
      if (this.match.getQues.test(this.url_main)) {
        console.log('问卷')
        this.currentPage = 'getQues'
        return 'getQues'
      }

    }

    console.log('没有匹配的路径')
    return false

  }

  toPage(page, cb) {
    let that = this
    
    // 执行getPageName判断用户是否已经登录
    this.getPageName()

    // 检查页面是否加载完成
    if (!this.isLoad) {
      console.log('页面未加载完成，不能跳转页面')
      return false
    }

    // 检查page是否在page列表内
    if (!_.has(this.match, page)) {
      console.log('非法的页面名称 ' + page)
      return false
    }

    // 检查page是否有权限跳转
    if (this._isNoJump(page)) {
      console.log('不能跳转到此页面 ' + page)
      return false
    }

    // 如果请求的是需要登录权限的页面则判断是否已经登录
    if (!this._isNoLogin(page) && !this.isLogin) {
      console.log('没有登陆，无权访问此页面')
      return false
    }

    switch(page) {
      case 'index':
        
        $(window).one('load', function() {
          console.log('跳转成功')
          that.isLoad = ture
          cb && cb(that)
        })

        window.location.href = this.url.index
        this.isLoad = false

        break
      case 'login':

        this.$content.one('load', function() {
          console.log('跳转login成功')
          that.isLoad = true
          cb && cb(that)
        })

        this.el_content.location.href = this.url.login
        this.isLoad = false

        break
      case 'reg':

        this.$content.one('load', function() {
          console.log('跳转reg成功')
          that.isLoad = true
          cb && cb(that)
        })

        this.el_content.location.href = this.url.reg
        this.isLoad = false

        break
      case 'welcome':

        this.$main.one('load', function() {
          console.log('跳转welcome成功')
          that.isLoad = true
          cb && cb(that)
        })

        this.el_main.location.href = this.url.welcome.main
        this.isLoad = false
        
        break
      case 'applicationReport':

        console.log(this.$main.length)

        this.$main.one('load', function() {
          console.log('跳转applicationReport成功')
          that.isLoad = true
          cb && cb(that)
        })

        this.el_main.location.href = this.url.applicationReport.main
        this.isLoad = false

        break
      case 'getReport':

        this.$main.one('load', function() {
          console.log('跳转getReport成功')
          that.isLoad = true
          cb && cb(that)
        })

        this.el_main.location.href = this.url.getReport.main
        this.isLoad = false

        break
      default:
        console.log('没有匹配的路径')
        return false
    }

  }
  
  // 处理来自后台代码的命令
  connect() {
    let that = this
    
    // 如果是报告页面则发送页面信息
    if (this.getPageName() === 'viewReport') {
      let el_error = document.querySelector('.erro_div1')

      if (el_error) {
        chrome.runtime.sendMessage({
          status: false,
          message: el_error.innerText
        }, function(response) {
          // 关闭报告页面
          if (response) {
            window.close()
          }
        })
      } else {
        chrome.runtime.sendMessage({
          status: true,
          data: {
            // 基本信息
            no              : $.trim($('.p').eq(0).text().split('：')[1]),
            queryTime       : $.trim($('.p').eq(1).text().split('：')[1]),
            reportTime      : $.trim($('.p').eq(2).text().split('：')[1]),
            name            : $.trim($('.p').eq(3).text().split('：')[1]),
            certificateType : $.trim($('.p').eq(4).text().split('：')[1]),
            certificateNo   : $.trim($('.p').eq(5).text().split('：')[1]),
            marry           : $.trim($('.p').eq(6).text()),
            // 概述
            outline: {
              // 信用卡
              creditCard: {
                // 账户数
                count: $.trim($('table').eq(7).find('td').eq(5).text()),
                // 未结清/未销户账户数
                uncleared: $.trim($('table').eq(7).find('td').eq(9).text()),
                // 发生过逾期的账户数
                overdue: $.trim($('table').eq(7).find('td').eq(13).text()),
                // 发生过90天以上逾期的账户数
                overdue90: $.trim($('table').eq(7).find('td').eq(17).text()),
                // 为他人担保笔数
                guarantee: $.trim($('table').eq(7).find('td').eq(21).text())
              },
              // 购房贷款
              house: {
                // 账户数
                count: $.trim($('table').eq(7).find('td').eq(6).text()),
                // 未结清/未销户账户数
                uncleared: $.trim($('table').eq(7).find('td').eq(10).text()),
                // 发生过逾期的账户数
                overdue: $.trim($('table').eq(7).find('td').eq(14).text()),
                // 发生过90天以上逾期的账户数
                overdue90: $.trim($('table').eq(7).find('td').eq(18).text()),
                // 为他人担保笔数
                guarantee: $.trim($('table').eq(7).find('td').eq(22).text())
              },
              // 购房贷款
              other: {
                // 账户数
                count: $.trim($('table').eq(7).find('td').eq(7).text()),
                // 未结清/未销户账户数
                uncleared: $.trim($('table').eq(7).find('td').eq(11).text()),
                // 发生过逾期的账户数
                overdue: $.trim($('table').eq(7).find('td').eq(15).text()),
                // 发生过90天以上逾期的账户数
                overdue90: $.trim($('table').eq(7).find('td').eq(19).text()),
                // 为他人担保笔数
                guarantee: $.trim($('table').eq(7).find('td').eq(23).text())
              },
            },
            // 信用卡信息
            creditCard: $('.h1:contains("信用卡")').next('ol')
                          .eq(0)
                          .find('li')
                          .text()
                          .split(/\n/)
                          .map(item => $.trim(item))
                          .filter(item => item.length),
            other: $('.h1:contains("其他贷款")').next('ol')
                    .eq(0)
                    .find('li')
                    .text()
                    .split(/\n/)
                    .map(item => $.trim(item))
                    .filter(item => item.length),
            public: $('.h1:contains("公共记录")')
                      .parent()
                      .next()
                      .find('ol')
                      .eq(0)
                      .find('li')
                      .text()
                      .split(/\n/)
                      .map(item => $.trim(item))
                      .filter(item => item.length),
            query: {
              organ: getOrgan(),
              own: getOwn()
            }
          }
        }, function(response) {
          // 关闭报告页面
          if (response) {
            window.close()
          }
        })

        function getOrgan() {
          let organ = $('.h1:contains("查询记录")')
                        .parents('table')
                        .next('table')
                        .find('tr')
                        .eq(2)
                        .nextAll()
          
          let i   = 0,
              len = organ.length,
              result = []

          if (!len) {
            return []
          }

          for (; i < len; i++) {
            result.push(organ.eq(i).text().split(/\n/).map(item => $.trim(item)).filter(item => item.length))
          }

          result.pop()
          
          return result

        }

        function getOwn() {
          let own = $('.h1:contains("查询记录")')
                        .parents('table')
                        .next('table')
                        .next('table')
                        .find('tr')
                        .eq(2)
                        .nextAll()
          
          let i   = 0,
              len = own.length,
              result = []

          if (!len) {
            return []
          }

          for (; i < len; i++) {
            result.push(own.eq(i).text().split(/\n/).map(item => $.trim(item)).filter(item => item.length))
          }

          result.pop()
          
          return result
        }
      }

    }
    
    // 监听后台数据
    chrome.runtime.onConnect.addListener(function(port) { // 连接成功事件
      
      console.log('开启连接')
      that.port = port

      port.onMessage.addListener(function(res) { // 接收数据事件
        console.log(res)

        that.data = res.data
        that.stamp = res.stamp

        that.command(res.task, port)
      })

      port.onDisconnect.addListener(function() { // 断开连接事件
        console.log('断开连接')
      })

    })

  }
  
  // 处理后台发送过来的指令
  command(task, port) {
    let that = this

    console.log('task ' + task)

    console.log('开始处理命令')
    
    switch(task) {
      case 'quit':
        this._quit(port)
      case '2login':
        this._2login(port)
        break
      case '2reg':
        this._2reg(port)
        break
      case '2getReport':
        this._2getReport(port)
        break
      case 'getLoginValidImage':
        this._getLoginValidImage(port)
        break
      case 'getRegStep1ValidImage':
        this._getRegStep1ValidImage(port)
        break
      case 'getReportValidCode':
        this._getReportValidCode(port)
        break
      case 'inputLoginForm':
        this._inputLoginForm(port)
        break
      case 'inputRegStep1Form':
        this._inputRegStep1Form(port)
        break
      case 'getStep2ValidCode':
        this._getStep2ValidCode(port)
        break
      case 'inputRegStep2Form':
        this._inputRegStep2Form(port)
        break
      case 'applicationReport':
        this._applicationReport(port)
        break
      case 'inputQues':
        this._inputQues(port)
        break
      case 'inputReportForm':
        this._inputReportForm(port)
        break
      case 'getReport':
        this._getReport(port)
        break
      default:
        port.postMessage({
          stamp: that.stamp,
          status: false,
          message: '没有匹配的任务'
        })
    }

  }
  
  /* ========= 退出 ========= */
  _quit(port) {
    let that = this

    this.toPage('index', function() {
      port.postMessage({
        stamp: that.stamp,
        status: true
      })
    })
    
  }
  /* ========= 任务 ========= */
  // 跳转登录
  _2login(port) {
    let that = this

    this.toPage('login', function() {
      port.postMessage({
        stamp: that.stamp,
        status: true
      })
    })
  }

  _2reg(port) {
    let that = this

    this.toPage('reg', function() {
      port.postMessage({
        stamp: that.stamp,
        status: true
      })
    })
  }

  _2getReport(port) {
    let that = this
    
    if (!this.isLogin) {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '没有登录,无权访问此页面'
      })
    }

    this.toPage('getReport', function() {
      that._reload()

      $(that.el_main.document).find('#radiobutton3').attr('checked', false)
      $(that.el_main.document).find('#radiobutton2').attr('checked', false)
      $(that.el_main.document).find('#radiobutton1').attr('checked', true)

      port.postMessage({
        stamp: that.stamp,
        status: true
      })

    })

  }
  
  // 获取登录页面验证码图片
  _getLoginValidImage(port) {
    let that = this

    let cvs = $("<canvas width='100px' height='25px'></canvas>"),
        ctx = cvs[0].getContext("2d"),
        img = $('<img>')

    img
      .attr('src', '/imgrc.do?a=' + new Date().getTime() + ';')
      .one('load', function(e) {
        ctx.drawImage(img[0], 0 ,0)

        port.postMessage({
          stamp: that.stamp,
          status: true,
          data: {
            validImg: cvs[0].toDataURL()
          }
        })

      })
      .on('error', function(e) {
        console.log('获取图片失败')

        port.postMessage({
          stamp: that.stamp,
          status: false,
          message: '图片获取失败'
        })
      })

  }
  // 获取注册步骤一页面验证码图片
  _getRegStep1ValidImage(port) {
    this._getLoginValidImage(port)
  }

  
  // 填写登录页面表单
  _inputLoginForm(port) {
    let that = this
    
    // 如果不是登录页面则跳转到登录页面再操作
    if (this.currentPage !== 'login') {
      
      this.toPage('login', function() {
        checkLogin()
      })

    } else {
      checkLogin()
    }
    
    // 验证登录
    function checkLogin() {

      that._reload()

      that.$content.one('load', function() {
        // 重新获取页面元素
        that._reload()
        
        // 根据main元素判断是否登录成功
        if (!that.el_main) {
          port.postMessage({
            stamp: that.stamp,
            status: false,
            message: $.trim($(that.el_content.document).find('.erro_div3').text())
          })
        } else {

          that.toPage('applicationReport', function() {
            that._reload()

            // 判断是否已生成报告
            let status    = '',
                isWait    = $(that.el_main.document).find('#ApplicationOption1').attr('disabled') ? true : false,
                isFail    = false,
                isSuccess = $(that.el_main.document).find('#verifyCode').length ? true : false

            // status: 用户申请信用报告的状态
            // 
            // noApply 未申请
            // wait    申请了,等待中
            // success 报告成功
            // fail    验证未通过
            
            if (isWait) {
              status = 'wait'
            } else if (isFail) {
              status = 'fail'
            } else if (isSuccess) {
              status = 'success'
            } else {
              // 如果三个状态都没有则表示未申请
              status = 'noApply'
            }

            port.postMessage({
              stamp: that.stamp,
              status: true,
              data: {
                status: status
              }
            })

          })

        }

      })

      $(that.el_content.document).find('[name="loginname"]').val(that.data.user)
      $(that.el_content.document).find('[name="password"]').val(that.data.password)
      $(that.el_content.document).find('[name="_@IMGRC@_"]').val(that.data.valid)
      $(that.el_content.document).find('[name="loginForm"]').submit()
    }
  }

  // 填写注册步骤一表单
  _inputRegStep1Form(port) {
    let that = this

    // 如果不是注册步骤一页面则跳转到注册步骤一页面再操作
    if (this.currentPage !== 'regStep1') {

      this.toPage('reg', function() {
        checkLogin()
      })

    } else {
      checkLogin()
    }
    
    // 验证注册信息
    function checkLogin() {

      that.$content.one('load', function() {
        // 重新获取页面元素
        that.getPageName()
        that._reload()
        
        // 根据main元素判断是否登录成功
        if (that.currentPage === 'regStep1') {
          port.postMessage({
            stamp: that.stamp,
            status: false,
            message: $.trim($(that.el_content.document).find('#_error_field_').text())
          })
        } else {

          port.postMessage({
            stamp: that.stamp,
            status: true
          })

        }

      })

      // 勾选合同
      $(that.el_content.document).find('#servearticle').attr('checked', true)
      // 姓名
      $(that.el_content.document).find('#name').val(that.data.name)
      // 证件号码
      $(that.el_content.document).find('#certNo').val(that.data.certNo)
      // 验证码
      $(that.el_content.document).find('[name="_@IMGRC@_"]').val(that.data.valid)
      // 提交
      $(that.el_content.document).find('.regist_btn ').click()
    }
  }

  // 填写获取信用报告页面表单
  _inputReportForm(port) {
    let that = this
    
    // 如果不是登录页面则跳转到登录页面再操作
    if (this.currentPage !== 'getReport') {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '页面错误'
      })
    } else {
      checkLogin()
    }
    
    function checkLogin() {
      // 这个页面要验证弹出层
      that._reload()
      console.log(that.data)
      
      $(that.el_main.document).find('#tradeCode').val(that.data.valid)
      $(that.el_main.document).find('#nextstep').click()

      setTimeout(function() {
        let $el = $(that.el_main.document).find('#codeinfo')

        if ($.trim($el.text()).length) {
          port.postMessage({
            stamp: that.stamp,
            status: false,
            message: $.trim($el.text())
          })
        }
      }, 1000)

    }
  }

  // 获取注册步骤二验证码
  _getStep2ValidCode(port) {
    let that = this

    // 如果不是注册步骤一页面则跳转到注册步骤一页面再操作
    if (this.currentPage !== 'regStep2') {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '页面错误'
      })
    }

    // 手机号码
    $(that.el_content.document).find('#mobileTel').val(that.data.phone)
    // 点击获取验证码按钮
    $(that.el_content.document).find('#getCode').click()

    port.postMessage({
      stamp: that.stamp,
      status: true
    })

  }

  // 获取信用报告验证码
  _getReportValidCode(port) {
    let that = this

    // 如果不是注册步骤一页面则跳转到注册步骤一页面再操作
    if (this.currentPage !== 'getReport') {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '页面错误'
      })

      return
    }

    if ($(that.el_main.document).find('#tradecodeBu').val().indexOf('未收到') === -1) {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '倒计时中'
      })

      return
    }

    // 点击获取验证码按钮
    $(that.el_main.document).find('#tradecodeBu').click()

    port.postMessage({
      stamp: that.stamp,
      status: true
    })

  }

  // 填写注册步骤二表单
  _inputRegStep2Form(port) {
    let that = this

    // 如果不是注册步骤一页面则跳转到注册步骤一页面再操作
    if (this.currentPage !== 'regStep2') {

      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '页面错误'
      })

      return

    } else {
      checkLogin()
    }

    // 验证注册信息
    function checkLogin() {

      that.$content.one('load', function() {
        // 重新获取页面元素
        that.getPageName()
        that._reload()

        let message = '' 
        
        // 头部错误
        message += $.trim($(that.el_content.document).find('#_error_field_').text())
        // 用户名错误
        message += $.trim($(that.el_content.document).find('#loginNameInfo').text())
        // 密码错误
        message += $.trim($(that.el_content.document).find('#passwordInfo').text())
        // 重复密码错误
        message += $.trim($(that.el_content.document).find('#cfpasswordInfo').text())
        // 电子邮件
        message += $.trim($(that.el_content.document).find('#emailInfo').text())
        // 验证码错误
        message += $.trim($(that.el_content.document).find('#verifyCodeInfo').text())
        
        if (that.currentPage === 'regStep2') {
          port.postMessage({
            stamp: that.stamp,
            status: false,
            message: message
          })
        } else {

          port.postMessage({
            stamp: that.stamp,
            status: true
          })

        }

      })

      // 登录名
      $(that.el_content.document).find('#loginname').val(that.data.user)
      // 密码
      $(that.el_content.document).find('#pwd').val(that.data.password)
      // 重复密码
      $(that.el_content.document).find('#cfpwd').val(that.data.repassword)
      // 电子邮件
      $(that.el_content.document).find('#email').val(that.data.email)
      // 手机号码
      $(that.el_content.document).find('#mobileTel').val(that.data.phone)
      // 动态码
      $(that.el_content.document).find('#verifyCode').val(that.data.valid)
      // 提交
      $(that.el_content.document).find('#sub').click()

      setTimeout(function() {
        let $el = $(that.el_content.document).find('#verifyCodeInfo')
        if ($el.length) {
          port.postMessage({
            stamp: that.stamp,
            status: false,
            message: $.trim($el.text())
          })
        }
      }, 1000)
    }
  }

  // 申请报告
  // 1.前往申请页面
  // 2.根据页面元素判断是否已经申请过并在等待中
  // 3.如果在等待中则返回失败
  // 4.如果可以申请则填写问卷

  _applicationReport(port) {
    let that = this

    // 如果请求的是需要登录权限的页面则判断是否已经登录
    if (!this.isLogin) {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '未登录,无权访问此页面'
      })
      
      return false
    }

    this.toPage('applicationReport', function() {
      that._reload()

      //  判断用户是否已申请过报告
      if ($(that.el_main.document).find('#ApplicationOption1').attr('disabled')) {
        port.postMessage({
          stamp: that.stamp,
          status: false,
          message: '已经申请过报告,请等待'
        })

        return
      }

      that.$main.one('load', function() {

        that._reload()

        if (that.getPageName() === 'getQues') {
          console.log('我是问卷页面')

          port.postMessage({
            stamp: that.stamp,
            status: true,
            data: {
              // 倒计时
              limitTime: $(that.el_main.document).find('#limitTimeSpan').text(),
              ques: getQues()
            }
          })

          function getQues() {
            let ques  = [],
                $ques = $(that.el_main.document).find('.qustion ul li'),
                i     = 0,
                len   = $ques.length

            for (; i < len; i++) {
              let question = $('p:first-child', $ques.eq(i)).text(),
                  $answer  = $('input:radio', $ques.eq(i)),
                  answer   = [],
                  j        = 0,
                  jLlen    = $answer.length

              for (; j < jLlen; j++) {
                answer.push({
                  value: $answer.eq(j).val(),
                  text: $answer.eq(j).next().text()
                })
              }

              if (!answer.length) {
                continue
              }

              ques.push({
                question: question,
                answer: answer
              })

            }

            return ques
          }

        } else {
          port.postMessage({
            stamp: that.stamp,
            status: false
          })
        }

      })

      // 勾选按钮
      $(that.el_main.document).find('#radiobutton3').attr('checked', true)
      $(that.el_main.document).find('#ApplicationOption1').attr('checked', true)
      $(that.el_main.document).find('#ApplicationOption2').attr('checked', false)
      $(that.el_main.document).find('#ApplicationOption3').attr('checked', false)

      $(that.el_main.document).find('#nextstep').click()
      
    })
  }
  
  // 填写问卷
  _inputQues(port) {
    let that = this

    let i   = 0,
        len = this.data.answer.length

    that._reload()

    if (that.getPageName() !== 'getQues') {
      port.postMessage({
        stamp: that.stamp,
        status: false,
        message: '页面错误,当前不是问卷页面'
      })
    }

    for (; i < len; i++) {
      $(this.el_main.document).find(`[name="kbaList[${ i }].answerresult"]`).val(that.data.answer[i])
    }
    
    this.$main.one('load', function() {
      port.postMessage({
        stamp: that.stamp,
        status: true
      })
    })

    $(this.el_main.document).find('#id_next').click()

  }
  
  // 获取报告
  _getReport(port) {
    let that = this

    if (this.getPageName() === 'viewReport') {

      port.postMessage({
        stamp: that.stamp,
        status: true,
        data: {
          html: $(document).html()
        }
      })

    }
  }

  // 重新获取页面元素，包括DOM元素、页面url、jquery对象
  _reload(cb) {
    this.el_content  = window.frames['conFrame']
    this.$content    = $('#conFrame'),
    this.url_content = this.el_content && this.el_content.location.href
    this.el_main     = this.el_content && this.el_content.frames['mainFrame']
    this.$main       = this.el_content && $(this.el_content.document).find('#mainFrame'),
    this.url_main    = this.el_main && this.el_main.location.href

    cb && cb(this)
  }
  
  // 判断页面是否是需要登录的页面
  // true ： 表示是不需要登录的页面
  // false： 表示是需要登录的页面
  _isNoLogin(page) {
    let that = this,
        i    = 0,
        len  =  this.noLoginMatch.length

    for (; i < len; i++) {
      if (this.noLoginMatch[i] === page) {
        return true
      }
    }

    return false
  }
  
  // 判断页面是否能直接跳转
  // true： 表示不能直接跳转
  // false：表示可以直接跳转
  _isNoJump(page) {
    let that = this,
        i    = 0,
        len  =  this.noJumpMatch.length

    for (; i < len; i++) {
      if (this.noJumpMatch[i] === page) {
        return true
      }
    }

    return false

  }

}

let c = new Credit()

setInterval(function() {

  c.getPageName()

}, 1000)